import { login,userinfo,logout,wxlogin,binduser,binduserOpenid,getcodeurl,getcodev2,getSetting,Init,bindservice,scanresult,applyPay,applyPayUp} from '@/api/admin'
import {
  setAdminUserId,
  getAdminUserId,
  delAdminUserId,
  setAdminToken,
  getAdminToken,
  delAdminToken,
  setUsername,
  delUsername,
  setNickname,
  delNickname,
  setGender,
  setAvatar,
  delAvatar,
  setUserid,
  delUserid,
  setUserpassword,
  getUserpassword,
  delUserpassword,
  setsubject_id,
  delsubject_id,
  getsubject_id,
  getGZ,
  delGZ,
  setsubjectTitle,
  delsubjectTitle,
  delapplyid,
  setapplyid,
  delJurisdiction,
  setJurisdiction,
  setSetting,
  delSetting,
  setwxopenid,
  delisfacetimemkface,
  delisfacetimezxface,
  delisfacetimekjface,
  delisfacetimezsface,
  delisfacetime,
  delTi,
  delwxopenid,
  delisphoto,
  delGender,
  delExectSetting,
  setPhone,
  delexamSetting,
  dellearnObject
} from '@/utils/auth'
import { Message,MessageBox } from 'element-ui'
import router, {resetRouter,constantRoutes}from '@/router'
// import { resolve } from 'core-js/fn/promise'
const state = {
  adminUserId: '',
  adminToken: getAdminToken(),
  username: '',
  nickname: '',
  login_time: '',
  remark: '',
  password:'',
  roles: [],
  userinfor:{},
  permission:[],
  subjectList:[],
  Jurisdictions:{},
  Jurisdiction:{},
  headPicture:'',
}

const mutations = {
  SET_ADMINUSERID: (state, adminUserId) => {
    state.adminUserId = adminUserId
  },
  SET_ADMINPASSWORD: (state, password) => {
    state.password = password
  },
  SET_ADMINTOKEN: (state, adminToken) => {
    state.adminToken = adminToken
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_LOGINTIME: (state, login_time) => {
    state.login_time = login_time
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFOR:(state,userinfor)=>{
    state.userinfor = userinfor
  },
  SET_BTNPERMISSION(state,permission){
    state.permission = permission
  },
  SET_SUBJECTLIST(state,subjectList){
    state.subjectList = subjectList
  },
  SET_JURISDICTIONS:(state,Jurisdictions)=>{
    state.Jurisdictions = Jurisdictions
  },
  SET_JURISDICTION:(state,Jurisdiction)=>{
    state.Jurisdiction = Jurisdiction
  },
  SET_HEADPICETURE:(state,headPicture)=>{
    state.headPicture = headPicture
  },
}

const actions = {
  // 登录
  login({ commit,dispatch,state }, userInfo) {
    const {
      username,
      password,
      verify_id,
      verify_code,
      rememberMe
    } = userInfo
    if(rememberMe){
      setUserid(username)
      setUserpassword(password)
    }else{
      delUserid()
      delUserpassword()
    }
    return new Promise(async (resolve, reject) => {
     await login({
        username: username,
        password: password,
        verify_id: verify_id,
        verify_code: verify_code
      }).then(response => {
        const { data } = response
        
        commit('SET_ADMINUSERID', data.username)
        commit('SET_ADMINTOKEN', data.token)
        commit('SET_USERINFOR', data.apply)
        commit('SET_NICKNAME', data.nickname)
        commit('SET_LOGINTIME', data.login_time)
        commit('SET_ADMINPASSWORD', password)
        setPhone(data.phone)
        setAdminUserId(data.id)
        setAdminToken(data.token)
        setsubject_id(data.apply[0].subject_id)
        setsubjectTitle(data.apply[0].subjectTitle)
        setwxopenid(data.openid)
        setGender(data.gender)
        setapplyid(data.apply[0].applyid)
        // dispatch('subject/setSubject',data.apply,{root:true})
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  userInfo({ commit, state,rootState ,dispatch}) {
    return new Promise(async (resolve, reject) => {
      userinfo().then(async response => {
        const { data } = response
        const {member_info} = data
        const {
          username,
          nickname,
          apply,
          login_time,
          avatar,
          openid,
          gender,
          phone
        } = member_info
        // dispatch('permission/generateRoutes',{},{root:true})
        commit('SET_USERINFOR',apply)
        commit('SET_ADMINUSERID', username)
        commit('SET_NICKNAME', nickname)
        commit('SET_LOGINTIME', login_time)
        commit('SET_HEADPICETURE', avatar)
        setUsername(username)
        setNickname(nickname)
        setGender(gender)
        setPhone(phone)
        // setwxopenid(openid)
        // dispatch('subject/setJurisdictions',{},{ root:true })\
        let subid = getsubject_id()?getsubject_id():apply[0].subject_id
        await getSetting({subjectid:subid,gz:getGZ()?getGZ():apply[0].gz}).then(res=>{
          if(res.code==200){
            if(!res.data){
              delUsername()
              delNickname()
              delsubjectTitle()
              delapplyid()
              delsubject_id()
              delAvatar()
              delJurisdiction()
              delisphoto()
              return reject({error:'未设置考试出题规则，请联系管理员设置考试出题规则',code:1100})
              // return Message.error('未设置考试出题规则，请联系管理员设置考试出题规则')
            }
            
            let exclude_material = ''
            let learnisShow=true
            let subTitle = apply[0].subjectTitle
            apply.forEach(item=>{
              if(subid==item.subject_id){
                exclude_material=item.exclude_material
                subTitle=item.subjectTitle
              }
            })
            
            let initObj = rootState.admin.initObj
            if(exclude_material=='是'){
              learnisShow=false
            }else{
              if(initObj.exclude_material&&initObj.exclude_material.split(',').indexOf(subid+'')!=-1){
                learnisShow=false
              }else{
                learnisShow=true
              }
            }
            // console.log(subid,exclude_material,learnisShow);
            let arr = ['初级','中级','高级','技师']
            let http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :window.location.href.slice(0, window.location.href.indexOf('/user'))
            if(res.data.gz){
              commit('SET_JURISDICTIONS',res.data)
              let obj = res.data
              if(res.data.gz=='职业技能等级认定'&&(http.indexOf('qdjsxy')!=-1||http.indexOf('qiye')!=-1||http.indexOf('testtjy')!=-1)){
                // subTitle
                arr.map(item=>{
                  if(subTitle.indexOf(item)!=-1){
                    commit('SET_JURISDICTION',{
                      模拟考试:obj.模拟考试[item].模块展示,
                      正式考试:obj.正式考试[item].模块展示,
                      专项练习:obj.专项练习.模块展示,
                      课程学习:learnisShow
                    })
                  }
                })
              }else{
                commit('SET_JURISDICTION',{
                  模拟考试:obj.模拟考试.模块展示,
                  正式考试:obj.正式考试.模块展示,
                  专项练习:obj.专项练习.模块展示,
                  课程学习:learnisShow
                })
              }
            }else{
              commit('SET_JURISDICTIONS',{})
              commit('SET_JURISDICTION',{
                模拟考试:'',
                正式考试:'',
                专项练习:'',
                课程学习:'',
              })
            }
            resolve(data)
            // if(obj.模拟考试.模块展示=='显示'&&obj.正式考试.模块展示=='显示'){
            //   commit('SET_JURISDICTION','3')
            // }else if(obj.模拟考试.模块展示=='显示'){
            //   commit('SET_JURISDICTION','1')
            // }else if(obj.正式考试.模块展示=='显示'){
            //   commit('SET_JURISDICTION','2')
            // }
          }
        })
        
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_ADMINTOKEN', '')
        commit('SET_ROLES', [])
        delAdminUserId()
        delAdminToken()
        delUsername()
        delNickname()
        delsubjectTitle()
        delapplyid()
        delsubject_id()
        delAvatar()
        delJurisdiction()
        delisphoto()
        delisfacetimezsface()
        delisfacetimemkface()
        delisfacetimezxface()
        delisfacetimekjface()
        delisfacetime()
        resetRouter()
        delexamSetting()
        dellearnObject()
        // 重置访问的视图和缓存的视图
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  //微信登录
  WxLoginInfo({ commit,dispatch,state }, userinfo){
    return new Promise((resolve, reject) =>{
      wxlogin({userinfo}).then(response=>{
         const{data} = response
        if(response.code==200){
          commit('SET_ADMINUSERID', data.username)
          commit('SET_ADMINTOKEN', data.token)
          commit('SET_USERINFOR', data.apply)
          commit('SET_LOGINTIME', data.login_time)
          commit('SET_NICKNAME', data.nickname)
          setAdminUserId(data.id)
          setAdminToken(data.token)
          setwxopenid(data.openid)
          setsubject_id(data.apply[0].subject_id)
          setsubjectTitle(data.apply[0].subjectTitle)
          setGender(data.gender)
          setPhone(data.phone)
        }
        resolve(response)
      }).catch(error=>{
        reject(error)
      })
    })
  },
  //微信绑定
  Wxbind({ commit}, userinfo){
    return new Promise(async (resolve, reject) =>{
      if(userinfo.unionid){
        await binduser(userinfo).then(response=>{
          if(response.code==200){
            const { data } = response
            // dispatch('permission/generateRoutes',{},{root:true})
            commit('SET_ADMINUSERID', data.username)
            commit('SET_ADMINTOKEN', data.token)
            commit('SET_USERINFOR', data.apply)
            commit('SET_LOGINTIME', data.login_time)
            commit('SET_NICKNAME', data.nickname)
            setAdminUserId(data.id)
            setAdminToken(data.token)
            setwxopenid(data.openid)
            setsubject_id(data.apply[0].subject_id)
            setsubjectTitle(data.apply[0].subjectTitle)
            setGender(data.gender)
            setPhone(data.phone)
          }
          resolve(response)
        }).catch((err)=>{
          reject(err)
        })
      }else{
        await binduserOpenid(userinfo).then(response=>{
          if(response.code==200){
            const { data } = response
            // dispatch('permission/generateRoutes',{},{root:true})
            commit('SET_ADMINUSERID', data.username)
            commit('SET_ADMINTOKEN', data.token)
            commit('SET_USERINFOR', data.apply)
            commit('SET_LOGINTIME', data.login_time)
            commit('SET_NICKNAME', data.nickname)
            setAdminUserId(data.id)
            setAdminToken(data.token)
            setwxopenid(userinfo.openid)
            setsubject_id(data.apply[0].subject_id)
            setsubjectTitle(data.apply[0].subjectTitle)
            setGender(data.gender)
          setPhone(data.phone)
          }
          resolve(response)
        }).catch((err)=>{
          reject(err)
        })
      }
    })
  },
  //服务号绑定
  Wxbindservice({ commit}, userinfo){
    return new Promise((resolve, reject) =>{
      bindservice(userinfo).then(response=>{
        if(response.code==200){
          const { data } = response
          // dispatch('permission/generateRoutes',{},{root:true})
          commit('SET_ADMINUSERID', data.username)
          commit('SET_ADMINTOKEN', data.token)
          commit('SET_USERINFOR', data.apply)
          commit('SET_LOGINTIME', data.login_time)
          commit('SET_NICKNAME', data.nickname)
          setAdminUserId(data.id)
          setAdminToken(data.token)
          setsubject_id(data.apply[0].subject_id)
          setsubjectTitle(data.apply[0].subjectTitle)
          setGender(data.gender)
          setPhone(data.phone)
        }
        resolve(response)
      }).catch((err)=>{
        reject(err)
      })
    })
  },
  //服务号扫码识别
  scanresultservice({ commit,dispatch,state }, userinfo){
    return new Promise((resolve, reject) =>{
      scanresult(userinfo).then(res=>{
        if(res.code==200){
          if(res.msg=='未扫码'){
            
          }else if(res.msg=='请先绑定账号'){
            // this.$router.push('/wxbind?openid='+res.data.openid)
          }else{
            const {member} = res.data
            commit('SET_ADMINTOKEN', member.token)
            commit('SET_USERINFOR', member.apply)
            commit('SET_NICKNAME', member.nickname)
            commit('SET_LOGINTIME', member.login_time)
            commit('SET_ADMINUSERID', member.username)
            setAdminUserId(member.id)
            setAdminToken(member.token)
            setsubject_id(member.apply[0].subject_id)
            setsubjectTitle(member.apply[0].subjectTitle)
            setwxopenid(member.openid)
            setGender(member.gender)
            setPhone(member.phone)
          }
          resolve(res)
        }
      }).catch(error=>{
        reject(error)
      })
    })
  },
  //手机端微信获取个人信息
  wxlogin(){
    return new Promise((resolve,reject)=>{
      getcodeurl().then(res=>{
        resolve(res)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  //获取微信openid
  getcode(){
    return new Promise((resolve,reject)=>{
      getcodev2().then(res=>{
        resolve(res)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  //微信支付下单
  wxPayList({ commit },data){
    // const {openid,applyid} = data
    return new Promise(async (resolve,reject)=>{
      await applyPay(data).then(res=>{
        resolve(res)
      }).catch(err=>{
        reject(err)
      })
    })
    
  },
  //微信支付下单 通用
  wxPayListUp({ commit },data){
    // const {openid,applyid} = data
    return new Promise(async (resolve,reject)=>{
      await applyPayUp(data).then(res=>{
        resolve(res)
      }).catch(err=>{
        reject(err)
      })
    })
    
  },
  // 重置token
  resetAdminToken({ commit }) {
    return new Promise(resolve => {
      console.log(154);
      commit('SET_ADMINTOKEN', '')
      commit('SET_ROLES', [])
      delAdminUserId()
      delAdminToken()
      delGZ()
      delTi()
      delsubject_id()
      delGender()
      delisfacetimezsface()
      delisfacetimemkface();
      delisfacetimezxface();
      delisfacetimekjface();
      delisfacetime();
      delsubjectTitle()
      delapplyid()
      delSetting()
      delwxopenid()
      delisphoto()
      delExectSetting()
      delUserid()
      delUserpassword()
      delexamSetting()
      dellearnObject()
      resolve()
    })
  },
  //清除储存记录
  resetSeccson({ commit }){
    return new Promise(resolve => {
      delAdminUserId()
      delGZ()
      delTi()
      // delsubject_id()
      delGender()
      delisfacetimezsface()
      delisfacetimemkface();
      delisfacetimezxface();
      delisfacetimekjface();
      delisfacetime();
      // delsubjectTitle()
      // delapplyid()
      delSetting()
      delwxopenid()
      delisphoto()
      delExectSetting()
      delUserid()
      delUserpassword()
      resolve()
    })
  },
  //切换存入权限
  commitJurisdiction({ commit },data){
    commit('SET_JURISDICTION',data)
  },
  //切换工种科目时 重新赋值
  commitJurisdictions({ commit },data){
    commit('SET_JURISDICTIONS',data)
  },
  //初始化 设置名称
  initfunction({ commit,dispatch }){
    return new Promise(async (resolve, reject)=>{
      await Init().then(res=>{
        if(res.code==200){
          document.title =res.data.alias
          dispatch('setinitData',res.data, { root: true })
          resolve(res.data)
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
